/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

import Helpers.ControleExec;
import java.util.Vector;
import javax.bluetooth.BluetoothStateException;
import javax.bluetooth.DataElement;
import javax.bluetooth.DeviceClass;
import javax.bluetooth.DiscoveryAgent;
import javax.bluetooth.DiscoveryListener;
import javax.bluetooth.LocalDevice;
import javax.bluetooth.RemoteDevice;
import javax.bluetooth.ServiceRecord;
import javax.bluetooth.UUID;

/**
 *
 * @author Lilli
 */
public class ClientBt implements Runnable, DiscoveryListener {

    DiscoveryAgent disc = null;
    boolean completedDevices = true, completedServices = true;
    public Vector services = null, usersName = null;
    public ControleExec devices = null;
    String userName;
    String[] Vizinhos;
    RmiClient client;
    public int servicosAchados;
    public boolean completedServicesSearch;
    public int networkId;

    public ClientBt(RmiClient client, String username) {
        devices = new ControleExec();
        services = new Vector();
        usersName = new Vector();
        this.userName = username;
        usersName.addElement(userName);
        this.client = client;
        completedServicesSearch = false;
        servicosAchados = 0;
    }

    ClientBt(ClientBt client, String string) {
    }

    public void run() {

        services.removeAllElements();
        try {
            LocalDevice local = LocalDevice.getLocalDevice();
            local.setDiscoverable(DiscoveryAgent.GIAC);
            disc = local.getDiscoveryAgent();
            completedDevices = false;
            disc.startInquiry(DiscoveryAgent.GIAC, this);
        } catch (BluetoothStateException ex) {
            ex.printStackTrace();
        }
    }

    public void deviceDiscovered(RemoteDevice rd, DeviceClass dc) {
   //     System.out.println("Achou um dispositivo");
        devices.addDevice(rd);
    }

    public void inquiryCompleted(int i) {

        if (devices.size() == 0) {
            //System.out.println("Não foram encontrados dispositivos");
            completedServicesSearch = true;
            return;
            //statar servidor
        }
        switch (i) {
            case INQUIRY_COMPLETED:
             //  System.out.println("Completou inquisição!");
                completedDevices = true;
                int[] attributes = {0x100, 0x101, 0x102, 0x99, 0x98};

                UUID[] uuids = new UUID[2];
                uuids[0] = new UUID(0x1101);
                uuids[1] = new UUID("F0E0D0C0B0A000908070605040302010", false);
                for (int o = 0; o < devices.size(); o++) {
                  if(!completedServicesSearch)
                  {
                    RemoteDevice rd = devices.elementAt(o);
                    try {
                        completedServices = false;
                        disc.searchServices(attributes, uuids, rd, this);
                    } catch (BluetoothStateException ex) {
                        ex.printStackTrace();
                    }
                }
                }
                break;
            case INQUIRY_TERMINATED:
            //    System.out.println("Inqisição terminada pela aplicação!");
                break;
        }
    }

    public synchronized void serviceSearchCompleted(int trackID, int i1) {

        switch (i1) {
            case SERVICE_SEARCH_COMPLETED:

                break;

            case SERVICE_SEARCH_TERMINATED:
              //  System.out.println("Cancelou a busca de serviços!");
                break;
            case SERVICE_SEARCH_NO_RECORDS:
              //  System.out.println("Não foram achados servicos!");
                break;
        }

    }

    public synchronized void servicesDiscovered(int trackID, ServiceRecord[] srs) {
      //  System.out.println("Achou servicos");
        if (!completedServicesSearch) {
            for (int j = 0; j < srs.length; j++) {
                devices.removeDevice(srs[j].getHostDevice());
                System.out.println("Entrou!");
                String url = srs[j].getConnectionURL(ServiceRecord.NOAUTHENTICATE_NOENCRYPT, false);
                System.out.println(url);
                 try {
                    DataElement de = srs[j].getAttributeValue(0x99);
                    DataElement de2 = srs[j].getAttributeValue(0x98);
                    if (de != null) {
                        String str = (String) de.getValue();
                        int str2 =  Integer.parseInt((String)de2.getValue());
                        this.networkId = str2;

        //                System.out.println("Usuario :" + str + " Network Id :" + str2);
                        servicosAchados++;
                        client.requestSongs(this.userName, str2);
                        completedServicesSearch = true;
                    }
                } catch (Exception ex) {
                }
      //          System.out.println("Adicionando na lista o serviço :" + srs[j].getConnectionURL(ServiceRecord.NOAUTHENTICATE_NOENCRYPT, false));
                services.addElement(srs[j]);
       //         System.out.println("Devices size = " + devices.size());
                if (devices.size() == 0) {
                    completedServicesSearch = true;
                }
            }
        }
    }
}
